package com.hkts.naturalgasauthentication.base.controller;

/*import cn.exrick.xboot.common.utils.ResultUtil;
import cn.exrick.xboot.common.vo.Result;
import com.aliyuncs.CommonResponse;*/

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonResponse;
import com.hkts.naturalgasauthentication.base.dao.HontPostDao;
import com.hkts.naturalgasauthentication.base.entity.*;
import com.hkts.naturalgasauthentication.base.service.HontUserPostService;
import com.hkts.naturalgasauthentication.base.service.HontUserService;
import com.hkts.naturalgasauthentication.base.vo.UserRolePermissionVo;
import com.hkts.naturalgasauthentication.common.SecurityConstant;
import com.hkts.naturalgasauthentication.common.constant.CommonConstant;
import com.hkts.naturalgasauthentication.config.sms.AliyunSmsUtils;
import com.hkts.naturalgasauthentication.feign.FeignInterface;
import com.hkts.naturalgasauthentication.flowablevo.UserEntityImplVo;
import com.hkts.naturalgasauthentication.notification.entity.SubscribeMessageVO;
import com.hkts.naturalgasauthentication.notification.entity.WxMssVo;
import com.hkts.naturalgasauthentication.utils.*;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Transient;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/authentication")
public class UserController {
    @Autowired
    private SecurityUtil securityUtil;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AliyunSmsUtils aliyunSmsUtils;

    @Autowired
    private HontUserService hontUserService;
    @Autowired
    private FeignInterface feignInterface;



    @GetMapping("/test")
    public Map<String,Object> test(){
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("statu","ok");
        map.put("msg","成功！");
        return map;
    }
    /*
    *
    * */
    @RequestMapping("/performanceUserInfo")
    public Result<Object> performanceUserInfo(){
        Map<String,Object> map=new HashMap<String,Object>();
        String s = redisTemplate.opsForValue().get(CommonConstant.CACHE + securityUtil.getCurrUser() + CommonConstant.CACHE_IDENTITY);
       if(StrUtil.isBlank(s)){
           UserRolePermissionVo userRolePermissionVo = hontUserService.getUserRolePermissionVo();
           List<HontRole> roles = userRolePermissionVo.getRoles();
           if(roles==null||roles.size()==0){
               return ResultUtil.data(0);}

           Integer identity=0;
           for(int i=0;i<roles.size();i++){
               if(identity<roles.get(i).getLevel()){
                   identity=roles.get(i).getLevel();
               }
           }
           map.put("identity",identity);
           redisTemplate.opsForValue().set(CommonConstant.CACHE + securityUtil.getCurrUser() + CommonConstant.CACHE_IDENTITY,identity.toString(),7200,TimeUnit.SECONDS);
       }else{
           map.put("identity",Integer.parseInt(s));
       }
        return ResultUtil.data(map);
    }
    //UserRolePermissionVo  绩效用的用户信息
    @RequestMapping("/userInfo")
    public Result<Object> userInfo(){
        HontUser currUser = securityUtil.getCurrUser();
        currUser.setPassword(null);
       return ResultUtil.data(currUser);
    }
    //用于远程调用用户信息
    @RequestMapping("/remoteUserInfo")
    public HontUser remoteUserInfo(){
        HontUser currUser = securityUtil.getCurrUser();
        return currUser;
    }
    //注册获取验证码
    @RequestMapping(value = "/mobileRigist", method = RequestMethod.GET)
    public Result<Object> mobileRigist(String mobileNum) throws  Exception{
        List<HontUser> users = hontUserService.customFind(mobileNum);
        if(users.size()>0){
            return ResultUtil.error("该手机已经注册！");
        }
        int code=  (int) Math.round((Math.random() + 1) * 1000);
        //CommonResponse commonResponse = aliyunSmsUtils.sendSms(mobileNum, code);
        CommonResponse commonResponse = aliyunSmsUtils.sendSms(mobileNum,code);
        String captchaId = UUID.randomUUID().toString().replace("-","");
        String s = redisTemplate.opsForValue().get(mobileNum);
        if(s!=null){
            return ResultUtil.data(commonResponse.getData());
        }else{
            redisTemplate.opsForValue().set(mobileNum, code+"",2L, TimeUnit.MINUTES);
            return ResultUtil.data(code);
        }

    }
    @Transient
    @RequestMapping(value = "/regist",method = RequestMethod.POST)
    public Result<Object> regist(HontUser u,String code){
        List<HontUser> users = hontUserService.customFind(u.getMobile());

        if(users.size()>0){
            return ResultUtil.error("该手机已经注册！");
        }
        String redisCode = redisTemplate.opsForValue().get(u.getMobile());
        if(redisCode==null||!redisCode.equals(code)){
            return ResultUtil.error(501,"验证码错误！");
        }
        if(StrUtil.isBlank(u.getNickName()) || StrUtil.isBlank(u.getPassword())){
            return ResultUtil.error("缺少必需表单字段");
        }

        if(hontUserService.findByUsername(u.getUserName())!=null){
            return ResultUtil.error("该用户名已被注册");
        }

        String encryptPass = new BCryptPasswordEncoder().encode(u.getPassword());
        String s = IDUtils.genImageName();
        u.setId(s);
        u.setStatus(CommonConstant.USER_STATUS_NORMAL.toString());
        u.setUserName(u.getMobile());
        u.setApprove(CommonConstant.ING);
        u.setPassword(encryptPass);
        u.setType(CommonConstant.USER_TYPE_NORMAL);
        u.setCreateTime(new Date());
        HontUser user=hontUserService.saveUser(u);

        if(user==null){
            return ResultUtil.error("注册失败");
        }
        /*同步到远程flow数据库*/
        UserEntityImplVo userVo=new UserEntityImplVo();
        userVo.setId(user.getId());
        userVo.setFirstName(user.getNickName());
        userVo.setDisplayName(user.getNickName());
        userVo.setLastName(user.getNickName());
        userVo.setEmail(user.getEmail());
        userVo.setRevision(0);
        userVo.setPassword(user.getPassword());
        Map<String, Object> save = feignInterface.save(userVo);
        if (!save.get("code").toString().equals("100")) {
            throw new RuntimeException("数据同步失败");
        }
                
       /* // 默认角色
        List<Role> roleList = roleService.findByDefaultRole(true);
        if(roleList!=null&&roleList.size()>0){
            for(Role role : roleList){
                UserRole ur = new UserRole();
                ur.setUserId(user.getId());
                ur.setRoleId(role.getId());
                userRoleService.save(ur);
            }
        }*/

        return ResultUtil.data(user);
    }
    //手机短信验证
    @RequestMapping(value = "/mobileNumber", method = RequestMethod.GET)
    public Result<Object> mobileNumber(String mobileNum) throws  Exception{
        int code=  (int) Math.round((Math.random() + 1) * 1000);
        CommonResponse commonResponse = aliyunSmsUtils.sendSms(mobileNum,code);
        String captchaId = UUID.randomUUID().toString().replace("-","");
        String s = redisTemplate.opsForValue().get(mobileNum);
        if(s!=null){
            return ResultUtil.data(commonResponse.getData());
        }else{
            redisTemplate.opsForValue().set(mobileNum, code+"",2L, TimeUnit.MINUTES);
            return ResultUtil.data(code);
        }
    }
    @RequestMapping(value = "/frontModifyPass",method = RequestMethod.POST)
    public Result<Object> frontModifyPass( @RequestParam String newPass, String code, String mobile){

        HontUser user = hontUserService.findByMobile(mobile);
        if (user == null){
            return ResultUtil.error("该手机号还未注册！");
        }
        String sessionCode =redisTemplate.opsForValue().get(mobile);
        if(!CustomStringUtils.isNotBlank(sessionCode)||!sessionCode.equals(code)){
            return ResultUtil.error("验证码错误！");
        }
        String newEncryptPass= new BCryptPasswordEncoder().encode(newPass);
        user.setPassword(newEncryptPass);
        hontUserService.updatePassword(user);


        return ResultUtil.success("修改密码成功");
    }
    @RequestMapping({"/doLogout"})
    public Result<Object> logout(HttpServletRequest request, HttpServletResponse response) {
        HontUser currUser = securityUtil.getCurrUser();
        String userName = currUser.getUserName();
       // redisTemplate.opsForValue().set(SecurityConstant.USER_TOKEN + username, token, tokenProperties.getSaveLoginTime(), TimeUnit.DAYS);
        String token = redisTemplate.opsForValue().get(SecurityConstant.USER_TOKEN + userName);
        redisTemplate.delete(SecurityConstant.TOKEN_PRE + token);
        redisTemplate.delete(SecurityConstant.USER_TOKEN + userName);
        return ResultUtil.success("退出登录");
    }
    //拉黑
    @RequestMapping (value = "/disable")
    public String blank(String userName) {
            // redisTemplate.opsForValue().set(SecurityConstant.USER_TOKEN + username, token, tokenProperties.getSaveLoginTime(), TimeUnit.DAYS);
            String token = redisTemplate.opsForValue().get(SecurityConstant.USER_TOKEN + userName);
            redisTemplate.delete(SecurityConstant.TOKEN_PRE + token);
            redisTemplate.delete(SecurityConstant.USER_TOKEN + userName);
        return "200";
    }
    //换绑手机
    @RequestMapping(value = "/changeMobile",method = RequestMethod.POST)
    public Result<Object> changeMobile(String mobile,String code){
        String sessionCode =redisTemplate.opsForValue().get(mobile);
        if(!CustomStringUtils.isNotBlank(sessionCode)||!code.equals(sessionCode)){
            return ResultUtil.error("验证码错误");
        }
        List<HontUser> byMobile = hontUserService.customFind(mobile);
        boolean status=true;
        for(int i=0;i<byMobile.size();i++){
            if(byMobile.get(i).getMobile().equals(mobile)){
                status=false;
                break;
            }
        }
        if(status){
            HontUser u = securityUtil.getCurrUser();
            u.setMobile(mobile);
            u.setUserName(mobile);
            hontUserService.updateMobile(u);
            return ResultUtil.success("修改成功");
        }else{
            return ResultUtil.error("该手机号已经绑定");
        }
    }

//    @RequestMapping(value = "/updatePass",method = RequestMethod.POST)
//    public Result<Object> updatePass( @RequestParam String newPass,String oldPass,String mobile,String code){
//        String sessionCode =redisTemplate.opsForValue().get(mobile);
//        if(!CustomStringUtils.isNotBlank(sessionCode)||!code.equals(sessionCode)){
//            return ResultUtil.error("验证码错误");
//        }
//        if(!newPass.equals(oldPass)){
//            return ResultUtil.error("两次密码输入不正确");
//        }
//
//        HontUser hontUser = hontUserService.cutomerfindByMobile(mobile);
//        hontUser.setPassword();
//        hontUserService.updatePassword(hontUser);
//        return ResultUtil.success("修改密码成功");
//    }
    @RequestMapping(value = "/updateNewPass",method = RequestMethod.POST)
    public Result<Object> updatePassWord( @RequestParam String newPass,String oldPass){
        HontUser user = securityUtil.getCurrUser();
        if(!new BCryptPasswordEncoder().matches(oldPass, user.getPassword())){
            return ResultUtil.error("旧密码不正确");
        }
        String newEncryptPass= new BCryptPasswordEncoder().encode(newPass);
        user.setPassword(newEncryptPass);
        hontUserService.updatePassword(user);
        return ResultUtil.success("修改密码成功");
    }

    @RequestMapping(value = "/updateNickName",method = RequestMethod.POST)
    public Result<Object> updateNickName(String nickName){
        HontUser u = securityUtil.getCurrUser();
        u.setNickName(nickName);
        hontUserService.updateNickname(u);
        return ResultUtil.success("修改成功");
    }
    //用户列表   用于流程服务用户的同步
    @RequestMapping(value = "/fontUserList",method = RequestMethod.GET)
    public List<HontUser> fontUserList(){
        List<HontUser> hontUsers = hontUserService.hontUserList();
        hontUsers.stream().forEach(hontUser -> {
            hontUser.setAvatar(null);
        });
        return   hontUsers;
    }

    //用户列表   用于流程服务用户的同步
    @RequestMapping(value = "/fontRoleList",method = RequestMethod.GET)
    public List<HontRole> fontRoleList(){
        List<HontRole> hontRole = hontUserService.hontRoleList();
        return   hontRole;
    }
    //用户列角色关联表   用于流程服务用户的同步
    @RequestMapping(value = "/hontUserRoles",method = RequestMethod.GET)
    public List<HontUserRole> hontUserRoles(){
        List<HontUserRole> hontUserRoles = hontUserService.hontUserRoleList();
        return   hontUserRoles;
    }
    //用户列角色关联表   用于流程服务用户的同步s

    ////用户管理部门ids
    @RequestMapping(value = "/getDepartmentIds",method = RequestMethod.GET)
    public List<String> getDepartmentIds(){
        HontUser currUser = securityUtil.getCurrUser();
        List<String> range = redisTemplate.opsForList().range(CommonConstant.CACHE + currUser + CommonConstant.CACHE_DEPARTMENT, 0, -1);
        if(range==null||range.size()==0){
            range= hontUserService.getDepartmentIds();
            if(range.size()>0){
                redisTemplate.opsForList().leftPushAll(CommonConstant.CACHE + currUser + CommonConstant.CACHE_DEPARTMENT, range);
                redisTemplate.expire(CommonConstant.CACHE + currUser + CommonConstant.CACHE_DEPARTMENT,7200,TimeUnit.SECONDS);
            }
        }
        return   range;
    }
    /*
    * 用于后台操作后将前台缓存数据进行删除操作
    * */
    @RequestMapping(value = "/deleteCacheByUserId",method = RequestMethod.POST)
    public Result deleteCacheByUserId(String userId){
        String[] split = userId.split(",");
        for (int i = 0; i< split.length; i++){
            Set<String> keys = redisTemplate.keys(CommonConstant.CACHE + split[i]+"*");
            for (String key : keys) {
                redisTemplate.delete(key);
            }
        }

     return ResultUtil.success("删除成功！");
    }
    @GetMapping("/getAccessToken")
    public String getAccessToken() {
        if (redisTemplate.opsForValue().get("access_token") != null ){
            System.out.println(redisTemplate.opsForValue().get("access_token"));
            return redisTemplate.opsForValue().get("access_token");
        }
        RestTemplate restTemplate = new RestTemplate();
        Map<String, String> params = new HashMap<>();
        params.put("APPID", "wx3e1d6f5c08a3aac7");  //
        params.put("APPSECRET", "b8e6c6441a3a26aaf3cbe5774483d544");  //
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(
                "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={APPID}&secret={APPSECRET}", String.class, params);
        String body = responseEntity.getBody();
        JSONObject jsonObject = JSON.parseObject(body);
        String Access_Token = jsonObject.getString("access_token");
        String expires_in = jsonObject.getString("expires_in");
        System.out.println("有效时长expires_in：" + expires_in);
        /*String appId = "wx3e1d6f5c08a3aac7";
        String appSecret = "b8e6c6441a3a26aaf3cbe5774483d544";
        String result = cn.hutool.http.HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret);
        cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(result);
        String access_token = jsonObject.getStr("access_token");*/
        redisTemplate.opsForValue().set("access_token",Access_Token,7140, TimeUnit.SECONDS);
        return Access_Token;
    }
    /*public String getAccessToken() {
        String appId = "wx3e1d6f5c08a3aac7";
        String appSecret = "b8e6c6441a3a26aaf3cbe5774483d544";
        String result = cn.hutool.http.HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        return jsonObject.getStr("access_token");
    }*/

    /**
     * 发送订阅消息
     *
     * @param
     */
    @GetMapping("/send")
    public String  sendMessage(@RequestBody String[] openId) {
        HontUser currUser = securityUtil.getCurrUser();
        String nickName = currUser.getNickName();
        if (openId.length > 0 || openId != null){
            for (int i = 0; i < openId.length; i++){
                    RestTemplate restTemplate = new RestTemplate();
                    String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + getAccessToken();
                    SubscribeMessageVO bean = new SubscribeMessageVO();
                    SimpleDateFormat formatter  = new SimpleDateFormat("yyyy-MM-dd");
                    String format = formatter.format(new Date());
                    bean.setThing13(new SubscribeMessageVO.Thing13("您有一条来自" + nickName + "待办未处理"));
                    bean.setThing1(new SubscribeMessageVO.Thing1("请及时处理"));
                    bean.setTime7(new SubscribeMessageVO.Time7(format));
                    WxMssVo wxMssVO = new WxMssVo();
                    wxMssVO.setTouser(openId[i]);
                    wxMssVO.setTemplate_id("yLsH8sIZUhzLouHXJVq3HOKq5f47Ia8OUwxKzXQxy3Y");//模板id号码
                    wxMssVO.setData(bean);
                    /*wxMssVO.setAppid("wx3e1d6f5c08a3aac7");*/
                try {
                    restTemplate.postForEntity(url, wxMssVO, String.class);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        return "";
    }
    @GetMapping("/end")
    public String  sendEnd(@RequestBody String[] o) {
        HontUser currUser = securityUtil.getCurrUser();
        String nickName = currUser.getNickName();
        if (o.length > 0 || o != null){
            for (int i = 0; i < o.length; i++){
                RestTemplate restTemplate = new RestTemplate();
                String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + getAccessToken();
                SubscribeMessageVO bean = new SubscribeMessageVO();
                SimpleDateFormat formatter  = new SimpleDateFormat("yyyy-MM-dd");
                String format = formatter.format(new Date());
                bean.setThing13(new SubscribeMessageVO.Thing13("您有一条来自" + nickName + "的考核信息"));
                bean.setThing1(new SubscribeMessageVO.Thing1("请及时查阅"));
                bean.setTime7(new SubscribeMessageVO.Time7(format));
                WxMssVo wxMssVO = new WxMssVo();
                wxMssVO.setTouser(o[i]);
                wxMssVO.setTemplate_id("yLsH8sIZUhzLouHXJVq3HOKq5f47Ia8OUwxKzXQxy3Y");//模板id号码
                wxMssVO.setData(bean);
                /*wxMssVO.setAppid("wx3e1d6f5c08a3aac7");*/
                try {
                    ResponseEntity<String> responseEntity =
                            restTemplate.postForEntity(url, wxMssVO, String.class);
                    return responseEntity.getBody();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        return "";
    }
}
